package com.webreport.webapp.tag;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;

import org.apache.commons.lang.StringUtils;

import com.webreport.webapp.bean.PaginationFilter;

public class PagingTag extends SimpleTagSupport {
	
	private String href = "";
	
	// 当前页
	private String cparam = "currentPage";
	// 每页条数
	private String sparam = "rowsPerPage";
	
	private int curr;// 当前页
	
	private int size;// 每页条数
	
	private int total;// 总页数
	PaginationFilter pagination;
	
	public void doTag() throws JspException, IOException {
		JspWriter out = getJspContext().getOut();
		
		if (StringUtils.isEmpty(cparam)) {
			cparam = "currentPage";
		}
		if (StringUtils.isEmpty(sparam)) {
			sparam = "pageSize";
		}
		
		if (!href.endsWith("?") && !href.endsWith("&")) {
			if (href.indexOf("?") == -1) {
				href = href + "?";
			} else {
				href = href + "&";
			}
		}
		
		if (curr <= 0) {
			curr = 1;
		} else if (curr > total) {
			curr = total;
		}
		
		out.append("<ul class=\"page-numbers\">");
		// 首页
		if (total > 0) {
			// 上一页
			if (curr > 1) {
				href(out, href, "prev", curr - 1, "&nbsp;");
			} else {
				href(out, href, "prev", 1, "&nbsp;");
			}
			for (int i = 1; i <= total; i++) {
				if (i != curr)
					href(out, href, "", i, String.valueOf(i));
				else
					href(out, href, "active", i, String.valueOf(i));
			}
			if (this.curr < this.total) {
				href(out, href, "next", curr + 1, "&nbsp;");
			} else {
				href(out, href, "next", this.total, "&nbsp;");
			}
			out.append("</ul>");
		}
		super.doTag();
	}
	
	private void href(JspWriter out, String href, String style, int curr, String title) throws IOException {
		out.append("<li");
		if (!StringUtils.isEmpty(style)) {
			out.append(" class=\"").append(style).append("\"");
		}
		out.append(">");
		if (!StringUtils.isEmpty(href)) {
			out.append("<a href=\"").append(href).append(cparam).append("=").append("" + curr).append("&").append(sparam).append("=").append("" + size).append("\">");
			out.append(title);
			out.append("</a>");
		}
		out.append("</li>");
	}
	
	public int getCurr() {
		return curr;
	}
	
	public void setCurr(int curr) {
		this.curr = curr;
	}
	
	public int getTotal() {
		return total;
	}
	
	public void setTotal(int total) {
		this.total = total;
	}
	
	public String getHref() {
		return href;
	}
	
	public void setHref(String href) {
		this.href = href;
	}
	
	public String getCparam() {
		return cparam;
	}
	
	public void setCparam(String cparam) {
		this.cparam = cparam;
	}
	
	public String getSparam() {
		return sparam;
	}
	
	public void setSparam(String sparam) {
		this.sparam = sparam;
	}
	
	public int getSize() {
		return size;
	}
	
	public void setSize(int size) {
		this.size = size;
	}
	
}